const https = require('https');

 
const SQLHelper = require('./SQLHelper')
const snowflake = require('./snowflake')
const {formatTime} = require('./util')




module.exports = function(app){
   
    function loginRouter(req,res,next){

        if(req.method.toUpperCase() == 'OPTIONS'){
            next()
            return;
        }

        let token = req.headers.token
        if(token){
            SQLHelper(`select * from session where id = ${token} and state = 1`).then(ret => {
                if(ret.length){
                    let session = ret[0]
                  
                    if(new Date().getTime() - session.createTime < 2*60*60*1000){
                        req.session = {
                            userId:session.userId,
                            userName:session.userName
                        }
                        next()
                    }else{
                        res.status(400).send({errorMsg:'登录超时'})
                    }              
                }else{
                    res.status(400).send({errorMsg:'当前用户未登录'})
                }
            })
        }else{
            res.status(400).send({errorMsg:'缺少token,请先登录'})
        }
    }
    


    app.use('/admin',loginRouter)
    

    app.post('/login', (req, res) => {
        let userName = req.body.userName
        let passWord = req.body.passWord
        if(userName && passWord){
            SQLHelper(`
            select * from user where userName= '${userName}'
            `).then(users => {
                if(users.length){
                    let user = users[0]
                    if(passWord == user.passWord){
                        let token = snowflake()
                        SQLHelper(`
                            INSERT INTO session(id,userId,userName,inTime,createTime,platform)
                            VALUES(${token},'${user._id}','${user.nickName}','${formatTime(new Date())}',${new Date().getTime()},'admin')
                        `).then(ret => {
                            res.send({
                                nickName:user.nickName,
                                token,
                                avatarUrl:user.photo,
                                _id:user._id
                            })
                        })
                    }else{
                        res.send({errorMsg:'密码错误'})
                    }
                }else{
                    res.send({errorMsg:'当前用户不存在'})
                }
            })
        }else{
            res.send({errorMsg:'用户名和密码不能为空'})
        }
    
    })

    app.get('/admin/logout',(req,res) => {
        SQLHelper(`
            update session set outTime = '${formatTime(new Date())}' , state = 0
            where id =${req.headers.token}
        `).then(ret => {
            res.send({msg:'退出登录成功'})
        })
    })



    app.post('/admin/changePassWord',(req,res) => {
        let userId = req.session.userId,
            passWord = req.body.passWord,
            newPassWord = req.body.newPassWord
            if(passWord && newPassWord){
              
                SQLHelper(`
                    select passWord from user where _id = ${userId}
                `).then(users => {
                    let user = users[0]
                   
                    if(user.passWord == passWord){
                       
                        SQLHelper(`
                            update user set passWord = '${newPassWord}' where _id = ${userId}
                        `).then(ret => {
                            res.send({msg:'修改密码成功'})
                        })
                    }else{
                        res.send({errorMsg:'原密码错误'})
                    }
                })
            }else{
                res.send({errorMsg:'原密码和新密码不能为空'})
            }
        
    })
  
   app.get('/admin/index',(req,res)=>{
       let pageSize = req.query.pageSize || 10
       let pageNum = req.query.pageNum || 1
       let offset = (pageNum - 1) * pageSize
       let title = req.query.title
       let type = req.query.type
       let whereSql = 'from index_region where state = 1'
      
       if(type) whereSql += ` and type = '${type}'`
       
       if(title) whereSql += ` and title like "%${title}%"`
        SQLHelper(`select count(*) as total ${whereSql};select * ${whereSql} limit ${pageSize} offset ${offset}`).then(ret => {
        res.send({
            total:ret[0][0].total,
            rows:ret[1]
        })
       })
   })


    
    app.post('/admin/index', (req, res) => {
        let  img = req.body.img,url = req.body.url,status = req.body.status 
        let  type = req.body.type || 'banner',title = req.body.title
        if(type != 'banner' && !title){
            res.send({errorMsg:'标题不能为空'})
            return
        }
        if(status != 1)  status = 0
        if (img) {
            let createTime = new Date().getTime()
            SQLHelper(`
            INSERT INTO index_region(title,img,url,status,state,createTime,unitId,type)
            VALUES('${title}','${img}','${url}','${status}',1,'${createTime}','juzao','${type}')
            `).then(ret => {
                res.send(ret.insertId ? {_id:ret.insertId}:{errorMsg:'新增数据失败'})
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })




    
    app.put('/admin/index', (req, res) => {
        if (req.body.indexId) {
           
            let updateTime = new Date().getTime()
            let updateKey = ['img','url','title','status']
            let updateValues = [`updateTime=${updateTime}`]
            for(let i = 0;i<updateKey.length;i++){
                let Key = updateKey[i],value = req.body[Key]
                if(value !== undefined){
                    updateValues.push(`${Key} = '${value}'`)
                }
            }
            SQLHelper(`UPDATE index_region set ${updateValues.join(',')} WHERE _id = ${req.body.indexId}`).then(ret => {
                res.send(ret)
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })

  
    app.delete('/admin/index', (req, res) => {
        let indexId = req.query.indexId 
        if (indexId) {
                    SQLHelper(`
                    UPDATE index_region
                    set state = 0
                    WHERE _id = ${indexId}
                    `).then(ret => {
                        res.send(ret)
                    })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })
}




